using System;
using System.IO;
using System.ServiceProcess;
using System.Threading;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Common;
using Config;
using System.Diagnostics;

namespace FileTransfer
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        ServiceController sc = null;
        bool isRun = false;
        string taskNo = "";
        string logGetPath = "";
        string logUploadPath = "";

        #region 页面初始化
        private void AppMainForm_Load(object sender, EventArgs e)
        {
            try
            {
                Version v = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
                string ver = "V" + v.Major.ToString() + "." + v.Minor.ToString() + "." + v.Revision.ToString().Substring(0, 1);
                this.Text = SystemSet.AppName + ver;
                this.SetServiceStatus();
                this.BindTasks();
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, "初始化错误！错误原因："+ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion

        #region 操作
        private void btnStart_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.sc != null && this.sc.Status == ServiceControllerStatus.Stopped)
                {
                    this.sc.Start();
                    this.SetServiceStatus();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, "启动错误！错误原因：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.sc != null && this.sc.Status != ServiceControllerStatus.Stopped)
                {
                    this.sc.Stop();
                    this.SetServiceStatus();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, "停止错误！错误原因：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

      

        private void btnAdd_Click(object sender, EventArgs e)
        {
            try
            {
                TaskForm f = new TaskForm();
                f.IsEdit = false;
                f.ShowDialog(this);
                this.BindTasks();
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, "操作出错！错误原因：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            string taskNo = "";
            string op = "";
            try
            {
                if (this.lvTask.CheckedItems.Count == 1)
                {
                    taskNo = this.lvTask.CheckedItems[0].SubItems[0].Text.Trim();
                    op = this.lvTask.CheckedItems[0].SubItems[1].Text.Trim();
                    if (op == "Get")
                    {
                        TaskForm f = new TaskForm();
                        f.IsEdit = true;
                        f.TaskNo = taskNo;
                        f.OpType = OperateType.Get;
                        f.ShowDialog(this);
                    }
                    else if (op == "Send")
                    {
                        TaskForm f = new TaskForm();
                        f.IsEdit = true;
                        f.TaskNo = taskNo;
                        f.OpType = OperateType.Send;
                        f.ShowDialog(this);
                    }
                    this.BindTasks();
                }
                else
                    MessageBox.Show(this, "请选择一条您要修改的数据！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, "操作出错！错误原因：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnDel_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.lvTask.CheckedItems.Count == 0)
                {
                    MessageBox.Show(this, "请选择您要删除的数据！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                if (MessageBox.Show(this, "确定要删除吗？", "询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                {
                    string oldCorpNos = SystemSet.GetTaskNos;
                    foreach (ListViewItem item in this.lvTask.CheckedItems)
                    {
                        string corpNo = item.SubItems[0].Text.Trim();
                        string taskType = item.SubItems[1].Text.Trim();
                        if (corpNo != "")
                        {
                            if(taskType == "Get")
                                SystemSet.DelTaskNo(corpNo);
                            else if (taskType == "Send")
                                SystemSet.DelUploadTaskNo(corpNo);
                        }
                    }
                    this.BindTasks();
                    if (this.isRun && oldCorpNos != SystemSet.GetTaskNos)
                        MessageBox.Show(this, "系统正在运行中，要使改动马上生效，请先停止服务，然后重新启动！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, "操作出错！错误原因：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnRefreshLog_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.lvTask.CheckedItems.Count == 1)
                {
                    string taskNo = this.lvTask.CheckedItems[0].SubItems[0].Text.Trim();
                    this.ShowLog(taskNo);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, "操作出错！错误原因：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnLogRoot_Click(object sender, EventArgs e)
        {
            try
            {
                string folderPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory , SystemSet.LogPath);
                if (Directory.Exists(folderPath))
                    System.Diagnostics.Process.Start("explorer.exe", folderPath);  

            }
            catch (Exception ex)
            {
                MessageBox.Show(this, "操作出错！错误原因：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void tsmiService_Click(object sender, EventArgs e)
        {
            try
            {
                ServiceForm s = new ServiceForm();
                s.ShowDialog(this);
                this.SetServiceStatus();
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, "操作出错！错误原因：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void tsmiAbout_Click(object sender, EventArgs e)
        {
            AboutForm a = new AboutForm();
            a.ShowDialog(this);
        }

        private void tsmiUpdate_Click(object sender, EventArgs e)
        {
            try
            {
                AutoUpdate.FrmUpdate fu = new AutoUpdate.FrmUpdate();
                if (fu.HasNewVersion())
                {
                    if (MessageBox.Show("有新版本，是否要更新？", "更新", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        if (this.sc != null && this.sc.Status != ServiceControllerStatus.Stopped)
                            this.sc.Stop();
                        Process.Start(Path.Combine(Application.StartupPath, "updater.exe"));
                        Application.DoEvents();
                        Application.Exit();
                    }
                }
                else
                    MessageBox.Show(this, "当前已是最新版本！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void tsmiExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        #endregion

        #region 公共方法
        /// <summary>
        /// 获取服务状态
        /// </summary>
        private void SetServiceStatus()
        {
            ServiceController[] scServices = ServiceController.GetServices();
            this.sc = null;
            foreach (ServiceController scTemp in scServices)
            {
                if (scTemp.ServiceName == SystemSet.AppServiceName)
                {
                    this.sc = scTemp;
                    if (scTemp.Status == ServiceControllerStatus.Running)
                    {
                        this.isRun = true;
                        this.btnStart.Enabled = false;
                        this.btnStop.Enabled = true;

                        this.lbServiceStatus.Text = "已启动";
                        this.lbServiceStatus.ForeColor = Color.Green;
                    }
                    else
                    {
                        this.isRun = false;

                        this.btnStart.Enabled = true;
                        this.btnStop.Enabled = false;

                        this.lbServiceStatus.Text = "未启动";
                        this.lbServiceStatus.ForeColor = Color.Red;
                    }
                    break;
                }
            }
            if (this.sc == null)
            {
                this.btnStart.Enabled = false;
                this.btnStop.Enabled = false;

                this.lbServiceStatus.Text = "服务未安装";
                this.lbServiceStatus.ForeColor = Color.Blue;
            }
        }

        /// <summary>
        /// 显示任务列表
        /// </summary>
        private void BindTasks()
        {
            string[] taskNos = null;
            string[] sendTaskNos = null;

            this.lvTask.Items.Clear();
            this.lvTask.Columns.Clear();

            this.lvTask.Columns.Add("任务代码", 200, HorizontalAlignment.Center);
            this.lvTask.Columns.Add("任务类型", 100, HorizontalAlignment.Center);
            this.lvTask.Columns.Add("任务状态", 80, HorizontalAlignment.Center);
            this.lvTask.Columns.Add("轮询时间", 80, HorizontalAlignment.Right);
            this.lvTask.Columns.Add("任务方式", 80, HorizontalAlignment.Center);

            SystemSet.ClearCache();
            if (SystemSet.GetTaskNos != "")
                taskNos = SystemSet.GetTaskNos.Split(',');
            if (SystemSet.UploadTaskNos != "")
                sendTaskNos = SystemSet.UploadTaskNos.Split(',');

            for (int i = 0; taskNos != null && i < taskNos.Length; i++)
            {
                string msgGetSet = SystemSet.GetGetThreadSet(taskNos[i]);
                if (msgGetSet == "1")
                    msgGetSet = "开启";
                else
                    msgGetSet = "关闭";
                string msgGetThreadTime = SystemSet.GetGetThreadTime(taskNos[i]).ToString();

                string getMode = SystemSet.GetGetMsgMode(taskNos[i]);
                if (getMode == "0")
                    getMode = "Local";
                else if (getMode == "1")
                    getMode = "Ftp";
                else if (getMode == "2")
                    getMode = "Email";
                else if (getMode == "3")
                    getMode = "MSMQ";
                else if (getMode == "4")
                    getMode = "ActiveMQ";
                else
                    getMode = "Other";

                ListViewItem item = new ListViewItem(new string[] { taskNos[i], "Get", msgGetSet, msgGetThreadTime, getMode});
                this.lvTask.Items.Add(item);
            }

            for (int i = 0; sendTaskNos != null && i < sendTaskNos.Length; i++)
            {
                string msgUploadSet = SystemSet.GetUploadThreadSet(sendTaskNos[i]);
                if (msgUploadSet == "1")
                    msgUploadSet = "开启";
                else
                    msgUploadSet = "关闭";
                string msgUploadThreadTime = SystemSet.GetUploadThreadSetTime(sendTaskNos[i]).ToString();

                string uploadMode = SystemSet.GetUoloadMsgMode(sendTaskNos[i]);
                if (uploadMode == "0")
                    uploadMode = "Ftp";
                else if (uploadMode == "1")
                    uploadMode = "Email";
                else if (uploadMode == "2")
                    uploadMode = "MSMQ";
                else if (uploadMode == "3")
                    uploadMode = "ActiveMQ";
                else
                    uploadMode = "Other";

                ListViewItem item = new ListViewItem(new string[] { sendTaskNos[i], "Send", msgUploadSet, msgUploadThreadTime, uploadMode});
                this.lvTask.Items.Add(item);
            }
        }

        /// <summary>
        /// 获取日志文件路径
        /// </summary>
        /// <param name="taskNo"></param>
        /// <returns></returns>
        private string GetLogFilePath(string taskNo,string opType)
        {
            string getLogPath = Path.Combine(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, SystemSet.LogPath),Path.Combine("Get",taskNo));
            string uploadLogPath = Path.Combine(Path.Combine(AppDomain.CurrentDomain.BaseDirectory ,SystemSet.LogPath),Path.Combine("Send", taskNo));
            string root = "";
            string[] files = null;
            string file = "";

            if (opType == "Get")
                root = this.GetLastDirectory(getLogPath);
            else if (opType == "Send")
                root = this.GetLastDirectory(uploadLogPath);
            if (!string.IsNullOrEmpty(root))
                files = Directory.GetFiles(root, "*", SearchOption.TopDirectoryOnly);
            if (files != null && files.Length > 0)
                file = OrderFile.GetOrderFiles(files)[files.Length - 1];
            return file;
        }

        /// <summary>
        /// 获取排序最新目录
        /// </summary>
        /// <param name="root"></param>
        /// <returns></returns>
        private string GetLastDirectory(string root)
        {
            string[] directorys = null;
            string res = "";

            if (Directory.Exists(root))
            {
                directorys = Directory.GetDirectories(root, "*", SearchOption.TopDirectoryOnly);
                if (directorys != null && directorys.Length > 0)
                    res = GetLastDirectory(OrderFile.GetOrderFiles(directorys)[directorys.Length - 1]);
                else
                    res = root;
            }
            return res;
        }

        /// <summary>
        /// 显示log
        /// </summary>
        /// <param name="taskNo"></param>
        private void ShowLog(string taskNo)
        {
            string getLogPath = this.GetLogFilePath(taskNo, "Get");
            string uploadLogPath = this.GetLogFilePath(taskNo, "Send");
            if (File.Exists(getLogPath))
            {
                this.tbGetLog.Text = File.ReadAllText(getLogPath, Encoding.Default);
                this.logGetPath = getLogPath;
                this.ttGet.SetToolTip(this.tbGetLog, "任务代码：" + taskNo + "，文件名：" + Path.GetFileName(getLogPath));
            }
            else
            {
                this.tbGetLog.Text = "";
                this.logGetPath = "";
            }

            if (File.Exists(uploadLogPath))
            {
                this.tbUploadLog.Text = File.ReadAllText(uploadLogPath, Encoding.Default);
                this.logUploadPath = uploadLogPath;
                this.ttUpload.SetToolTip(this.tbUploadLog, "任务代码：" + taskNo + "，文件名：" + Path.GetFileName(uploadLogPath));
            }
            else
            {
                this.tbUploadLog.Text = "";
                this.logUploadPath = "";
            }
            this.taskNo = taskNo;
        }
        #endregion

        #region 公共事件
        private void timer_Tick(object sender, EventArgs e)
        {
            try
            {
                this.SetServiceStatus();
            }
            catch (Exception ex)
            {
               
            }
        }

        private void tabControlMain_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (this.tabControlMain.SelectedTab.Name == "tabPageStatus" && this.lvTask.SelectedItems.Count == 1)
                {
                    string taskNo = this.lvTask.SelectedItems[0].SubItems[0].Text.Trim();
                    this.ShowLog(taskNo);
                }
                else
                {
                    this.taskNo = "";
                    this.logGetPath = "";
                    this.logUploadPath = "";
                    this.tbGetLog.Text = "";
                    this.tbUploadLog.Text = "";

                    this.BindTasks();
                }
            }
            catch { }
        }

        private void lvTask_ColumnClick(object sender, ColumnClickEventArgs e)
        {
            try
            {
                ListView lv = (ListView)sender;
                if (lv.Columns[e.Column].Tag == null)
                    lv.Columns[e.Column].Tag = true;
                bool tabK = (bool)lv.Columns[e.Column].Tag;
                if (tabK)
                    lv.Columns[e.Column].Tag = false;
                else
                    lv.Columns[e.Column].Tag = true;
                lv.ListViewItemSorter = new ListViewSorter(e.Column, lv.Columns[e.Column].Tag);
                lv.Sort();
            }
            catch { }
        }

        private void lvTask_ItemChecked(object sender, ItemCheckedEventArgs e)
        {
            e.Item.Selected = true;
        }
        #endregion

        /// <summary>
        /// 操作类型
        /// </summary>
        public enum OperateType
        {
            /// <summary>
            /// 其他操作
            /// </summary>
            Other,
            /// <summary>
            /// 获取
            /// </summary>
            Get,
            /// <summary>
            /// 发送
            /// </summary>
            Send
        }
    }

    /// <summary>
    /// ListView排序
    /// </summary>
    public class ListViewSorter : System.Collections.IComparer
    {
        private int col;
        private bool descK;
        public ListViewSorter()
        {
            col = 0;
        }
        public ListViewSorter(int column, object Desc)
        {
            descK = (bool)Desc;
            col = column;
        }
        public int Compare(object x, object y)
        {
            int tempInt = String.Compare(((ListViewItem)x).SubItems[col].Text, ((ListViewItem)y).SubItems[col].Text);
            if (descK)
                return -tempInt;
            else
                return tempInt;
        }
    }  
}
